﻿using BusinessEntity;
using BusinessEntity.xmglQuerryEntity;
using BusinessRepository;
using learun.util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{
    public class ProLiXiangRule
    {

        //项目首页报表
        public static async Task<(IEnumerable<dynamic>, int)> GetbidsectionIndexList(CProbidsectionQuerry querry, string strdepids)
        {
               string str = "";
            if (!(string.IsNullOrEmpty(querry.jsdw)))
            {
                str = str + " and BuildUnit like '%" + querry.jsdw + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.xmmc)))
            {
                str = str + " and xmmc like '%" + querry.xmmc + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.dxmc)))
            {
                str = str + " and dxmc like '%" + querry.dxmc + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.xmbm)))
            {
                str = str + " and dxbm like '%" + querry.xmbm + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.status)))
            {
                str = str + " and spstatus = '" + querry.status + "'";
            }

            //做了立项的项目
            //str += " and id in (select xmid from CProManageLX)";
            //归档的项目
            str += " and id not in (select xmid from CProGD)";

            string strsql = "select * from View_ProLXLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = false;
            if (querry.sort == "Asc" || querry.sort == "asc")
            {
                isAsc = true;
            }
            if (string.IsNullOrEmpty(querry.column))
            {
                querry.column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(strsql, null, querry.column, isAsc, querry.size, querry.current);

        }

        //项目首页报表
        public static async Task<(IEnumerable<dynamic>, int)> GetXMlxIndexList(CProManageQuerry querry, string strdepids)
        {
         

            string str = "";
            if (!(string.IsNullOrEmpty(querry.jsdw)))
            {
                str = str + " and BuildUnit like '%" + querry.jsdw + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.xmmc)))
            {
                str = str + " and xmmc like '%" + querry.xmmc + "%'";
            }
            if (!(string.IsNullOrEmpty(querry.xmfl)))
            {
                str = str + " and xmflname = '" + querry.xmfl + "'";
            }
            if (!(string.IsNullOrEmpty(querry.zjly)))
            {
                str = str + " and zjly = '" + querry.zjly + "'";
            }
            if (!(string.IsNullOrEmpty(querry.year)))
            {
                str = str + " and xmnf = '" + querry.year + "'";
            }
            if (!(string.IsNullOrEmpty(querry.status)))
            {
                str = str + " and spstatus = '" + querry.status + "'";
            }

            //做了立项的项目
            str += " and id in (select xmid from CProManageLX)";
            //归档的项目
            str += " and id not in (select xmid from CProGD)";

            string strsql = "select * from View_ProLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = false;
            if (querry.sort == "Asc" || querry.sort == "asc")
            {
                isAsc = true;
            }
            if (string.IsNullOrEmpty(querry.column))
            {
                querry.column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(strsql, null, querry.column, isAsc, querry.size, querry.current);

        }

        public static async Task<(IEnumerable<dynamic>,int)> GetXMDXIndexList(dynamic dye, string strdepids)
        {
            
            string jsdw = dye.jsdw;
            string xmmc = dye.xmmc;
            string dxmc = dye.dxmc;
            string xmlx = dye.xmlx;
            string year = dye.year;

            //添加一个选择
            string hascg = dye.hascg;

            int current = dye.current;
            int size = dye.size;

            string sort = dye.sort ?? "";
            string column = dye.column ?? "";

            string str = "";
            if (!(string.IsNullOrEmpty(jsdw)))
            {
                //str = str + " and BuildUnit = '" + jsdw + "'";
                str = str + " and departid = '" + jsdw + "'";
                
            }

            if (!(string.IsNullOrEmpty(xmmc)))
            {
                str = str + " and xmmc like '%" + xmmc + "%'";
            }
            if (!(string.IsNullOrEmpty(dxmc)))
            {
                str = str + " and dxmc like '%" + dxmc + "%'";
            }
            if (!(string.IsNullOrEmpty(xmlx)))
            {
                str = str + " and xmflname = '" + xmlx + "'";
            }
            if (!(string.IsNullOrEmpty(year)))
            {
                str = str + " and xmnf = '" + year + "'";
            }

            str += " and xmid not in (select xmid from CProGD)";

            //没有做采购的单项，采购申请
            if (!string.IsNullOrEmpty(hascg))
            {
                str += " and id not in (select dxid from CProZBLS)";

                str += " and status = '2'";
            }

            //await UserRule.GetUserDepid(uid)
            string sql = "select * from view_ProDXLists where (departid in " + strdepids + " or cqdwid in " + strdepids + ")" + str.Replace("''", "'");
            bool isAsc = true;
            if (sort != "Asc" && sort != "asc")
            {
                isAsc = false;
            }
            if (string.IsNullOrEmpty(column))
            {
                column = "id";
            }
            return await new RepositoryFactory().BaseRepository().FindList(sql, null, column, isAsc, size, current);

        }

        //固定单体/标段列表
        public static async Task<IEnumerable<dynamic>> GetBDListByXmid(string pid, string xmid)
        {
            string sql = "select * from CProManageLX where pid ='" + pid + "' and xmid = '" + xmid + "' order by id";
            return await new RepositoryFactory().BaseRepository().FindList(sql, null);
        }

        //固定单体/标段列表-树状
        public static async Task<List<dynamic>> GetBDLXByXmid(string xmid)
        {
            //DataTable dts = new DataTable();
            //dts.Columns.Add("id");
            //dts.Columns.Add("pid");
            //dts.Columns.Add("dxmc");
            //dts.Columns.Add("status");

            List<dynamic> lists = new List<dynamic>();

            string sql = "select * from CProManageLX where pid ='0' and xmid = '" + xmid + "' order by id";
            DataTable table = await new RepositoryFactory().BaseRepository().FindTable(sql, null);
            for (int num = 0; num < table.Rows.Count; num++)
            {
                //DataRow row = dts.NewRow();
                //row["id"] = table.Rows[num]["id"].ToString();
                //row["pid"] = table.Rows[num]["pid"].ToString();
                //row["dxmc"] = table.Rows[num]["dxmc"].ToString();
                dynamic d = new ExpandoObject();
                d.id = table.Rows[num]["id"].ToString();
                d.pid = table.Rows[num]["pid"].ToString();
                d.dxmc = table.Rows[num]["dxmc"].ToString();


                lists.Add(d);
            }
            return lists;
        }

        //固定单体/标段列表-树状
        public static async Task<List<dynamic>> GetBDTreeByXmid(string xmid)
        {
            //DataTable dts = new DataTable();
            //dts.Columns.Add("id");
            //dts.Columns.Add("pid");
            //dts.Columns.Add("dxmc");
            //dts.Columns.Add("status");

            List<dynamic> lists = new List<dynamic>();

            string sql = @"select *,(
case when exists(select 1 from CProZBLS where dxid = CProManageLX.id)
or exists(select 1 from CProZB where dxid = CProManageLX.id)
then '0'
else '1' end
)kxz,(select case when exists(select 1 from CProManageLXHB where dxid= CProManageLX.id) 
then '1' else  '0' end)gl from CProManageLX where pid ='0' and xmid = '" + xmid + "' order by id";
            DataTable table = await new RepositoryFactory().BaseRepository().FindTable(sql, null);
            for (int num = 0; num < table.Rows.Count; num++)
            {
                //DataRow row = dts.NewRow();
                //row["id"] = table.Rows[num]["id"].ToString();
                //row["pid"] = table.Rows[num]["pid"].ToString();
                //row["dxmc"] = table.Rows[num]["dxmc"].ToString();
                dynamic d = new ExpandoObject();
                d.id = table.Rows[num]["id"].ToString();
                d.pid = table.Rows[num]["pid"].ToString();
                d.dxmc = table.Rows[num]["dxmc"].ToString();

                d.kxz = table.Rows[num]["kxz"].ToString();
                d.gl = table.Rows[num]["gl"].ToString();

                d.lev = "1";

                //row["status"] = "1";
                //dts.Rows.Add(row);
                string pid = table.Rows[num]["id"].ToString();
                string sql2 = @"select *,(
case when exists(select 1 from CProZBLS where dxid = CProManageLX.id)
or exists(select 1 from CProZB where dxid = CProManageLX.id)
then '0'
else '1' end
)kxz,(select case when exists(select 1 from CProManageLXHB where dxid = CProManageLX.id) 
then '1' else '0' end)gl from CProManageLX where pid ='" + pid + "' and xmid = '" + xmid + "' order by id";
                DataTable table2 = await new RepositoryFactory().BaseRepository().FindTable(sql2, null);

                List<dynamic> ll = new List<dynamic>();
                for (int i = 0; i < table2.Rows.Count; i++)
                {
                    //DataRow row2 = dts.NewRow();
                    //row2["id"] = table2.Rows[i]["id"].ToString();
                    //row2["pid"] = table2.Rows[i]["pid"].ToString();
                    //row2["dxmc"] = table2.Rows[i]["dxmc"].ToString();
                    //row2["status"] = "2";
                    //dts.Rows.Add(row2);
                    dynamic dd = new ExpandoObject();
                    dd.id = table2.Rows[i]["id"].ToString();
                    dd.pid = table2.Rows[i]["pid"].ToString();
                    dd.dxmc = table2.Rows[i]["dxmc"].ToString();

                    dd.kxz = table2.Rows[i]["kxz"].ToString();
                    dd.gl = table2.Rows[i]["gl"].ToString();

                    dd.lev = "1";

                    ll.Add(dd);
                }
                d.childs = ll;

                lists.Add(d);
            }
            return lists;
        }
        //根据id查询单条数据
        public static async Task<dynamic> GetBDById(string keyValue)
        {
            string sql = @"select CProManageLX.*,xmmc,tzxz,CONVERT(varchar(100), begindate, 23)begindate,CONVERT(varchar(100), enddate, 23)enddate from  CProManageLX
left join (select id,xmmc,begindate,enddate,tzxz from CProManage)txm on CProManageLX.xmid = txm.id
where CProManageLX.id =  '" + keyValue + "'";

            sql = "select * from view_ProDXLists where id = '" + keyValue + "'";
            return await new RepositoryFactory().BaseRepository().FindEntity(sql, null);
        }

        //根据概算查询合并表
        public static async Task<List<CProManageLXHB>> GetlxHB(string gsid)
        {
            string strsql = "select * from CProManageLXHB where hbid = '" + gsid + "' ";
            List<CProManageLXHB> thb = (List<CProManageLXHB>)await new RepositoryFactory().BaseRepository().FindList<CProManageLXHB>(strsql);
            return thb;
        }
        //根据单项查询合并表
        public static async Task<List<CProManageLXHB>> GetlxHBbydxid(string dxid)
        {
            string strsql = "select * from CProManageLXHB where dxid = '" + dxid + "' ";
            List<CProManageLXHB> thb = (List<CProManageLXHB>)await new RepositoryFactory().BaseRepository().FindList<CProManageLXHB>(strsql);
            return thb;
        }

        //新增修改
        public static async Task<bool> InsertCProManageLX(CProManageLX prolx, string ope)
        {
            if (ope == "add")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    await irp.Insert(prolx);

                    return true;
                });
            }
            else
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    await irp.Update(prolx);

                    return true;
                });
            }
        }

        //新增修改
        public static async Task<bool> InsertCProManageLX(CProManageLX prolx, List<CProManageGS> gss, List<CProManageLXHB> lxhbs, string straction,string strope, string uid)
        {
            if (straction == "hb")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    if (strope == "add")
                    {
                        for (int i = 0; i < gss.Count; i++)
                        {
                            //先删除单项表
                            string strsql = "delete from CProManageLX where id in(select dxid from CProManageLXHB where hbid = '" + gss[i].id + "')";
                            await irp.ExecuteSql(strsql);

                            //再删除关联表
                            await irp.DeleteAny<CProManageLXHB>(new { hbid = gss[i].id });

                            //修改概算表
                            await irp.Update(gss[i]);
                        }

                        for (int i = 0; i < lxhbs.Count; i++)
                        {
                            //新增关联表
                            await irp.Insert(lxhbs[i]);
                        }



                        //新增单项表
                        await irp.Insert(prolx);
                    }
                    else
                    {
                        await irp.Update(prolx);
                    }

                    return true;

                });
            }
            return true;
        }

        //新增修改
        public static async Task<bool> InsertCProManageLX(CProManageLX prolx, CProManageGS gs, CProManageLXHB lxhb, string straction,string strope, string uid)
        {
            if (straction == "py")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    if (strope == "add")
                    {
                        //先删除单项表
                        string strsql = "delete from CProManageLX where id in(select dxid from CProManageLXHB where hbid = '" + gs.id + "')";
                        await irp.ExecuteSql(strsql);

                        //再删除关联表
                        await irp.DeleteAny<CProManageLXHB>(new { hbid = lxhb.hbid });

                        //新增关联表
                        await irp.Insert(lxhb);

                        //新增单项表
                        await irp.Insert(prolx);


                        //修改概算表
                        await irp.Update(gs);
                    }
                    else
                    {
                        await irp.Update(prolx);
                    }
                    return true;

                });
            }
            else if (straction == "cf")
            {
                return await TranstionRule.GetRunActionTransAsync(async irp =>
                {
                    if (strope == "add")
                    {
                        //新增关联表
                        await irp.Insert(lxhb);

                        //新增单项表
                        await irp.Insert(prolx);
                        //修改概算表
                        await irp.Update(gs);
                    }
                    else
                    {
                        await irp.Update(prolx);
                    }
                    return true;

                });
            }

            return true;
        }

        public static async Task<bool> UpdateCProManageLX(CProManageLX prolx, string uid)
        {
            if (await new RepositoryFactory().BaseRepository().Update(prolx) > 0)
            {
                return true;
            }
            else
            {
                throw new Exception("操作异常,影响行数为0");
            }
        }
        //删除多条
        public static async Task DeleteCProManageLXMulti(Root ids)
        {

            foreach (BaseDeleteMulti idm in ids.ids)
            {
                //string delsql = "delete from dbo.CProConBG where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"')" +
                //    "delete from dbo.CProConBZJ where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"')
                //    delete from dbo.CProConFKJH where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"')
                //    delete from dbo.CProFKMX where sqid in (select id from dbo.CProFKSQ where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"'))
                //    delete from dbo.CProFKSQ where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"')
                //    delete from dbo.CProJS where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"')
                //    delete from dbo.CProJG where htid in (select id from dbo.CProContract where dxid ='" + idm.id + @"')
                //    delete from dbo.CProContract where dxid ='" + idm.id + @"'
                //    delete from dbo.CProZB where dxid ='" + idm.id + @"'
                //    delete from CProManageLXHB where dxid = '" + idm.id + @"'
                //    delete from CProManageLX where id = '" + idm.id + @"'";

                string delsql = "exec deletedx '" + idm.id + "'";

                await new RepositoryFactory().BaseRepository().ExecuteSql(delsql);
            }

        }
    }
}
